package cn.le.javaNet;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 为每个链接的socket分配一个线程来处理
 *
 */
public class ServeOneJabber extends Thread{

    private Socket socket;
    private BufferedReader in;
    private PrintWriter out;

    public ServeOneJabber(Socket s) throws IOException {
        socket = s;
        in = new BufferedReader(
                new InputStreamReader(socket.getInputStream())
        );

        out = new PrintWriter(
                new BufferedWriter(
                        new OutputStreamWriter(socket.getOutputStream())
                )
        ,true);

        this.start();;
    }

    public void run()
    {
        while (true)
        {
            String str = null;
            try {
                str = in.readLine();
                if(str != null)
                {
                    if(str.equals("END"))
                    {
                        break;
                    }
                    System.out.println("Echoing: "+ str);
                    out.println(str);
                }
            } catch (IOException e) {
                try {
                    socket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

            }
        }
    }
}
class MultiJabberServer{

    public static void main(String[] args) throws IOException {

        ServerSocket s = new ServerSocket(8080);
        System.out.println("Server Started");
        while (true)
        {
            Socket socket = s.accept();
            new ServeOneJabber(socket);
        }
    }
}